﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Autofac;
using QQ2564874169.Core;
using QQ2564874169.Core.Lock;
using QQ2564874169.RelationalSql;
using QQ2564874169.RelationalSql.Dapper;
using QQ2564874169.RelationalSql.Trigger;
using QQ2564874169.TypeContainer.Autofac;

namespace TestConsole
{
    class Program
    {
        public static IContainer Container;

        static Program()
        {
            var b = new ContainerBuilder();
            var assemblies = Utils.GetAssemblies(name =>
                name.QQStartsWith("qq2564874169") ||
                name.QQStartsWith("testconsole"));
            var types = assemblies.SelectMany(a => a.GetTypes())
                .Where(t => t.IsClass && !t.IsAbstract && !t.IsGenericType && !t.Name.StartsWith("<"))
                .ToArray();
            b.RegisterTypes(types).AsImplementedInterfaces();
            b.Register(context => new MsSql(".", "cfbb", "sa", "123456")).AsImplementedInterfaces();
            b.RegisterType<TriggerPublisher>().AsSelf();
            b.RegisterType<TestWatchMember>().AsSelf();

            Container = b.Build();

            
        }

        static void Main(string[] args)
        {
            TriggerItem.CreateSchema(Container.Resolve<ISchemaCreater>());

            var monitor = new DbExecuteMonitor(new AutofacContainer(Container.BeginLifetimeScope()));
            monitor.LoadService(typeof(TriggerPublisher));
            monitor.Start();

            var subscr = new TriggerSubscriber(new AutofacContainer(Container.BeginLifetimeScope()));
            subscr.LoadService(typeof(TestWatchMember));
            subscr.Start();

            while ((Console.ReadLine() != "0"))
            {
                Parallel.For(0, 10, i =>
                {
                    using (var exec = Container.Resolve<IDbExecute>())
                    {
                        exec.Insert(new Member
                        {
                            Id = LongId.New(),
                            CreateTime = DateTime.Now,
                            RegName = Guid.NewGuid().ToString()
                        });
                    }
                });
            }

            Console.WriteLine("Completed.");
            Console.Read();
        }
    }

    public class TestWatchMember : IWatchInsertAfter<Member>
    {
        public void OnInsertAfter(Member model)
        {
            Console.WriteLine(model.RegName);
        }
    }
}

